﻿using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Shapes;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
using Rectangle = System.Drawing.Rectangle;

namespace CarbonFiberDetection.Model
{
    public class HalconWindowEx
    {
        /// <summary>
        /// System.Drawimg.Bitmap 转 Hobject
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static HObject BitmapToHObjectColor(Bitmap bmp)
        {
            HObject halcon_image = null;
            HOperatorSet.GenEmptyObj(out halcon_image);
            try
            {
                Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                HOperatorSet.GenImageInterleaved(out halcon_image, bmpData.Scan0, "bgr", bmp.Width, bmp.Height, -1,
                    "byte", bmp.Width, bmp.Height, 0, 0, -1, 0);
                bmp.UnlockBits(bmpData);

            }
            catch (System.Exception exp)
            {
                //Logger.Log("<BitmapToHObjectColor> 图像转换发生异常," + exp.ToString());
                return null;
            }

            return halcon_image;
        }
        /// <summary>
        /// HObject转Bitmap
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static Bitmap HObjectToBitmap(HObject image)
        {
            HTuple hred, hgreen, hblue, type, width, height;

            HOperatorSet.GetImagePointer3(image, out hred, out hgreen, out hblue, out type, out width, out height);

            Bitmap res = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            try
            {

                Rectangle rect = new System.Drawing.Rectangle(0, 0, width, height);
                BitmapData bitmapData = res.LockBits(rect, ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                int imglength = width * height;
                unsafe
                {
                    byte* bptr = (byte*)bitmapData.Scan0;
                    byte* r = ((byte*)hred.I);
                    byte* g = ((byte*)hgreen.I);
                    byte* b = ((byte*)hblue.I);
                    for (int i = 0; i < imglength; i++)
                    {
                        bptr[i * 4] = (b)[i];
                        bptr[i * 4 + 1] = (g)[i];
                        bptr[i * 4 + 2] = (r)[i];
                        bptr[i * 4 + 3] = 255;
                    }
                }

                res.UnlockBits(bitmapData);
            }
            catch (Exception ex)
            {
                res = null;
                throw ex;
            }
            return res;
        }
    }
}
